package com.xzixi.websocket.interceptablewebsocketdemo.websocket;

import com.xzixi.websocket.interceptablewebsocket.interceptor.ToClientInterceptor;
import com.xzixi.websocket.interceptablewebsocketdemo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.messaging.StompSubProtocolHandler;

import java.security.Principal;

/**
 * @author 薛凌康
 */
public class SessionIdRegistryInterceptor implements ToClientInterceptor {

    @Autowired
    private SessionIdRegistry sessionIdRegistry;

    @Override
    public void postHandle(WebSocketSession session, Principal principal, StompHeaderAccessor accessor, Object payload, StompSubProtocolHandler handler) {
        User user = (User) session.getAttributes().get("user");
        if (user==null) {
            return;
        }
        SimpMessageType type = accessor.getMessageType();
        if (SimpMessageType.CONNECT_ACK.equals(type)) {
            // 记录sessionId
            String username = user.getUsername();
            String sessionId = session.getId();
            sessionIdRegistry.registerSessionId(username, sessionId);
        }
    }

}
